<template>
	<a-modal
		v-model:open="modalVisible"
		:title="isVipUser ? 'VIP 会员信息' : 'VIP 兑换码'"
		:width="500"
		@ok="handleAction"
		@cancel="handleCancel"
		:confirmLoading="loading"
		:okText="isVipUser ? '知道了' : '立即兑换'"
		:cancelText="isVipUser ? undefined : '取消'"
		:showCancel="!isVipUser"
	>
		<div class="vip-modal-content">
			<!-- VIP用户信息展示 -->
			<div v-if="isVipUser" class="vip-info-section">
				<div class="vip-status-header">
					<div class="vip-badge">
						<CrownOutlined class="crown-icon" />
						<span class="vip-text">VIP 会员</span>
					</div>
					<div class="vip-status active">已激活</div>
				</div>

				<div class="vip-details">
					<div class="detail-item">
						<span class="label">会员等级：</span>
						<span class="value">{{ userRole === 'admin' ? '管理员' : 'VIP会员' }}</span>
					</div>
					<div class="detail-item" v-if="vipExpireTime">
						<span class="label">过期时间：</span>
						<span class="value expire-time">{{ formatExpireTime(vipExpireTime) }}</span>
					</div>
					<div class="detail-item" v-else>
						<span class="label">会员期限：</span>
						<span class="value">永久有效</span>
					</div>
					<div class="detail-item">
						<span class="label">享受特权：</span>
						<span class="value">{{ vipPrivileges.length }}项专属特权</span>
					</div>
				</div>

				<div class="vip-privileges">
					<h4>您当前享受的VIP特权：</h4>
					<div class="privileges-list">
						<div class="privilege-item" v-for="privilege in vipPrivileges" :key="privilege.id">
							<CheckCircleOutlined class="check-icon" />
							<span>{{ privilege.title }}</span>
						</div>
					</div>
				</div>
			</div>

			<!-- 非VIP用户兑换区域 -->
			<div v-else class="redeem-section">
				<div class="redeem-form">
					<a-form :model="redeemForm" layout="vertical">
						<a-form-item label="兑换码" required>
							<a-input
								v-model:value="redeemForm.redeemCode"
								placeholder="请输入VIP兑换码"
								size="large"
								:maxlength="32"
								@keyup.enter="handleAction"
								:disabled="loading"
							/>
						</a-form-item>
					</a-form>
				</div>

				<div class="vip-benefits">
					<div class="benefits-title">
						<CrownOutlined style="color: #ffd700; margin-right: 8px" />
						VIP特权一览
					</div>
					<div class="benefits-list">
						<div class="benefit-item" v-for="benefit in vipPrivileges" :key="benefit.id">
							<CheckCircleOutlined style="color: #52c41a; margin-right: 8px" />
							{{ benefit.title }}
						</div>
					</div>
				</div>
			</div>
		</div>
	</a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { CrownOutlined, CheckCircleOutlined } from '@ant-design/icons-vue'
import { exchangeVipUsingPost } from '@/api/userController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import dayjs from 'dayjs'

interface Props {
	visible: boolean
}

interface Emits {
	(e: 'update:visible', value: boolean): void
	(e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loginUserStore = useLoginUserStore()
const modalVisible = ref(false)
const loading = ref(false)

const redeemForm = reactive({
	redeemCode: '',
})

// 判断是否为VIP用户（考虑过期情况）
const isVipUser = computed(() => {
	const userRole = loginUserStore.loginUser?.userRole

	// 管理员永久有效
	if (userRole === 'admin') {
		return true
	}

	// 非VIP用户
	if (userRole !== 'vip') {
		return false
	}

	// VIP用户需要检查是否过期
	const expireTime = loginUserStore.loginUser?.vipExpireTime
	if (!expireTime) {
		// 没有过期时间，考虑为永久VIP
		return true
	}

	// 检查是否过期
	const now = dayjs()
	const expire = dayjs(expireTime)

	// 如果已过期，返回false
	return expire.isAfter(now)
})

// 获取用户角色
const userRole = computed(() => loginUserStore.loginUser?.userRole)

// 获取VIP过期时间
const vipExpireTime = computed(() => {
	// 如果是管理员，返回null表示永久有效
	if (userRole.value === 'admin') {
		return null
	}
	// 使用真实的VIP过期时间数据
	return loginUserStore.loginUser?.vipExpireTime || null
})

// VIP特权列表
const vipPrivileges = [
	{ id: 1, title: '无限制图片上传' },
	{ id: 2, title: '高级AI扩图功能' },
	{ id: 3, title: '专属云存储空间' },
	{ id: 4, title: '优先客服支持' },
	{ id: 5, title: '高速处理通道' },
	{ id: 6, title: '数据安全备份' },
]

// 监听props变化
watch(
	() => props.visible,
	(newVal) => {
		modalVisible.value = newVal
	},
	{ immediate: true }
)

// 监听modal状态变化
watch(modalVisible, (newVal) => {
	emit('update:visible', newVal)
})

// 处理主要操作
const handleAction = async () => {
	if (isVipUser.value) {
		// VIP用户点击"知道了"
		handleCancel()
		return
	}

	// 非VIP用户执行兑换逻辑
	if (!redeemForm.redeemCode.trim()) {
		message.error('请输入兑换码')
		return
	}

	loading.value = true
	try {
		// 调用后端API进行兑换码验证
		const res = await exchangeVipUsingPost({
			vipCode: redeemForm.redeemCode.trim(),
		})

		if (res.data.code === 0 && res.data.data === true) {
			message.success('兑换成功！恭喜您成为VIP用户！')
			emit('success')
			handleCancel()
		} else {
			message.error(res.data.message || '兑换失败，请检查兑换码是否正确')
		}
	} catch (error: any) {
		console.error('兑换失败:', error)
		const errorMessage = error?.response?.data?.message || error?.message || '兑换失败，请检查兑换码是否正确'
		message.error(errorMessage)
	} finally {
		loading.value = false
	}
}

// 取消操作
const handleCancel = () => {
	modalVisible.value = false
	redeemForm.redeemCode = ''
}

// 格式化过期时间
const formatExpireTime = (expireTime: string | Date) => {
	if (!expireTime) return '永久有效'
	const date = dayjs(expireTime)
	const now = dayjs()
	const diffDays = date.diff(now, 'day')

	if (diffDays > 0) {
		return `${date.format('YYYY-MM-DD HH:mm')} (还有${diffDays}天)`
	} else if (diffDays === 0) {
		return `${date.format('YYYY-MM-DD HH:mm')} (今天到期)`
	} else {
		return `${date.format('YYYY-MM-DD HH:mm')} (已过期)`
	}
}
</script>

<style scoped lang="scss">
.vip-modal-content {
	.vip-info-section {
		.vip-status-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 24px;
			padding: 16px;
			background: linear-gradient(135deg, #ffd700 0%, #ffb300 100%);
			border-radius: 12px;
			color: white;

			.vip-badge {
				display: flex;
				align-items: center;
				gap: 8px;

				.crown-icon {
					font-size: 24px;
				}

				.vip-text {
					font-size: 18px;
					font-weight: 600;
				}
			}

			.vip-status {
				padding: 4px 12px;
				background: rgba(255, 255, 255, 0.2);
				border-radius: 16px;
				font-size: 14px;
				font-weight: 500;

				&.active {
					background: rgba(82, 196, 26, 0.9);
				}
			}
		}

		.vip-details {
			margin-bottom: 24px;

			.detail-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px 0;
				border-bottom: 1px solid #f0f0f0;

				&:last-child {
					border-bottom: none;
				}

				.label {
					color: #666;
					font-size: 14px;
				}

				.value {
					color: #333;
					font-weight: 500;

					&.expire-time {
						color: #1890ff;
					}
				}
			}
		}

		.vip-privileges {
			h4 {
				color: #333;
				font-size: 16px;
				margin-bottom: 16px;
				display: flex;
				align-items: center;
				gap: 8px;
			}

			.privileges-list {
				display: grid;
				grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
				gap: 12px;

				.privilege-item {
					display: flex;
					align-items: center;
					gap: 8px;
					padding: 8px 12px;
					background: #f6ffed;
					border: 1px solid #b7eb8f;
					border-radius: 6px;
					color: #52c41a;
					font-size: 14px;

					.check-icon {
						font-size: 16px;
					}
				}
			}
		}
	}

	.redeem-section {
		.redeem-form {
			margin-bottom: 24px;
		}

		.vip-benefits {
			padding: 16px;
			background: linear-gradient(135deg, #fef9e7 0%, #fff7e6 100%);
			border-radius: 8px;
			border: 1px solid #ffe58f;

			.benefits-title {
				font-size: 16px;
				font-weight: 600;
				color: #d4821a;
				margin-bottom: 12px;
				display: flex;
				align-items: center;
			}

			.benefits-list {
				.benefit-item {
					display: flex;
					align-items: center;
					margin-bottom: 8px;
					color: #666;
					font-size: 14px;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}
	}
}

:deep(.ant-modal-header) {
	.ant-modal-title {
		display: flex;
		align-items: center;
		gap: 8px;
	}
}

// VIP用户的模态框头部样式
:deep(.ant-modal-header) {
	background: linear-gradient(135deg, #ffd700 0%, #ffb300 100%);
	color: white;
	border-radius: 6px 6px 0 0;

	.ant-modal-title {
		color: white;
		font-weight: 600;
	}
}
</style>
